﻿using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.Windows;
using VNet.VisiSuite.Common;
using VNet.VisiSuite.Common.Helper;
using VNet.VisiSuite.Common.Resource;
using VNet.VisiSuite.Common.Security;
using VNet.VisiSuite.Controls;
using VNet.VisiSuite.Service.Contact.Message.Security;
using VNet.VisiSuite.VisiAdmin.Common.Helpers;
using VNet.VisiSuite.VisiAdmin.Models;
using VNet.VisiSuite.VisiAdmin.Providers;
using VNet.VisiSuite.VisiAdmin.Views;

namespace VNet.VisiSuite.VisiAdmin.ViewModels
{
    public class LoginViewModel : BaseViewModel
    {
        #region Fields
        private LoginModel _model;
        private Visibility _visibility;

        #endregion

        public LoginViewModel()
        {
            LoginCommand = new RelayCommand(DoLogin);

            PageTitle = TitleString.LoginAdminTitle;
            TopRightButtonIcons = new ObservableCollection<VNetMenuItem> { new VNetMenuItem("Exit", "Exit VisiSuite", CommonConstants.VNetIcon.AppbarClose, VNetMenuItemType.WhiteBackgroundTheme, OnExit), };
        }

        #region Properties
        public RelayCommand LoginCommand { get; set; }

        public LoginModel Model
        {
            get { return _model; }
            set
            {
                _model = value;
                OnPropertyChanged("Model");
            }
        }

        public Visibility Visibility
        {
            get { return _visibility; }
            set
            {
                _visibility = value;
                OnPropertyChanged("Visibility");
            }
        }

        #endregion

        #region Methods
        private void DoLogin(object obj)
        {
            if (!Model.IsValid())
                return;

            IsBusy = true;
            DoAsync(SecurityProvider.Login, LoginCompleted, Model);
        }

        private void LoginCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            var result = (SignInResponse)e.Result;

            if (!result.Success && result.Error != null && (result.Error.ErrorCode == "Error InstallKey" || result.Error.Description == ErrorMessages.ServiceUrlInvalid))
            {
                DisplayRegistryFields(Visibility.Visible
                    , result.Error.ErrorCode == "Error InstallKey" ? string.Empty : Model.InstallKey.TrimSafety()
                    , result.Error.Description == ErrorMessages.ServiceUrlInvalid ? string.Empty : Model.ServiceUrl.TrimSafety());

                RegistryHelper.DeleteInstallKeyRegistry();
            }
            else
            {
                RegistryKey reg = RegistryHelper.OpenRegistryVisi(CommonConstants.RegistryVisiSuite, true);
                reg.SetValue(CommonConstants.RegistryInstallKey, Model.InstallKey.TrimSafety());
                reg.SetValue(CommonConstants.RegistryServiceUrl, Model.ServiceUrl.TrimSafety());
                reg.Close();

                App.DownloadLogoImage();

                DisplayRegistryFields(Visibility.Collapsed, Model.InstallKey.TrimSafety(), Model.ServiceUrl.TrimSafety());
            }                                               

            if (!result.Success)
            {
                IsBusy = false;
                ErrorMessage = result.Error.Description;
                return;
            }

            NavigationManager.LoggedInUser = result;
            UserTransportToken.UserIdentity.IPAddress = result.IPAddress;
            UserTransportToken.UserIdentity.Token = result.Token;
            UserTransportToken.UserIdentity.UserLoginId = result.UserLoginId;

            NavigationManager.NavigateTo(new PlantView(), null);
        }

        private void DisplayRegistryFields(Visibility visibility, string key = "", string url = "")
        {
            if (Model == null)
                return;

            Visibility = visibility;
            Model.InstallKey = key;
            Model.ServiceUrl = url;
        }

        private void OnExit()
        {
            NavigationManager.CloseProgram();
        }

        #endregion

        #region Navigation Framwork
        public override void OnNavigate(object obj)
        {
            Model = new LoginModel();

            //Check registry for CustomeURL
            if (!RegistryHelper.CheckRegistryInstallKeyExist())
                DisplayRegistryFields(Visibility.Visible);
            else
            {
                var reg = RegistryHelper.OpenRegistryVisi(CommonConstants.RegistryVisiSuite, false);
                DisplayRegistryFields(Visibility.Collapsed, reg.GetValue(CommonConstants.RegistryInstallKey).ToString(), reg.GetValue(CommonConstants.RegistryServiceUrl).ToString());
                reg.Close();
            }

#if DEBUG
            Model.UserName = "abutler";
            Model.Password = "12345";
#endif
            Model.ShouldValidate = true;
        }

        public override void OnLeave()
        {
        }
        #endregion
    }
}
